<template>
	<!--表格单选-->
	<el-row class="product">
  		<el-col :span="24">
  			<!--查询过滤条件-->
  			<el-form :inline="true" :model="conditionForm" ref="conditionForm" label-width="82px">
  				<el-form-item label="名称">				
					<m-input-auto-comp :inputData="conditionForm" :queryInterUrl="urlPaths.goodsQueryList" queryParamName="goodsName"/>
				</el-form-item>
				<el-button type="primary" size="small" icon="search" @click="queryTableData">查询</el-button>
			</el-form>
  		</el-col>
  		<el-col :span="24">
  			<!--表格数据展示-->
  			<div>
	  			<el-button type="primary" size="small" icon="plus" v-on:click="addFn">新增</el-button>
	  			<el-button type="primary" size="small" icon="edit" v-on:click="editFn">修改</el-button>
	  			<el-button type="primary" size="small" icon="delete" v-on:click="deleteFn">删除</el-button>
  			</div>
  			<div class="data-list">
				<m-table-complex :tableDatas="tableDatalist" :queryTableDataUrl="urlPaths.queryList" :queryTableDataParms="conditionForm" :tableColumn="tableColumn"
					ref="tableChild" @select-rowidx-handler="handleCurrentChange">
				</m-table-complex>
			</div>
  		</el-col>
  		<!--<el-col :span="24">-->
  			<!--新增和修改 dialog-->
			<el-dialog :title="dialogTitle" v-if="dialogVisible" :visible.sync="dialogVisible" customClass="customStyle">
				<el-form :model="configform" ref="configform" :rules="rules" label-width="100px">
					<el-form-item v-for="(columnValue, columnKey) in configform" :label="transAttrName(columnKey)" v-if="isEditEnabled(columnKey)">
						<el-col :span="18">
							<el-select v-if="isShowSelectList(columnKey)" v-model="configform[columnKey]" filterable placeholder="请选择"
								@change="onSelectedDrug(columnKey, configform[columnKey])">
								<el-option v-for="item in getSelectOption(columnKey)" :key="item.id" :label="item.name" :value="item.id"></el-option>
							</el-select>
							<div v-else-if="isShowMutliElem(columnKey)" v-for="multiSelectItem in mutliSelectOption" style="width:50%" >
								{{multiSelectItem.label}}: 
								<el-select filterable placeholder="请选择" v-model="multiSelectItem.selectedValue">
									<el-option v-for="val in multiSelectItem.values" :key="val.id" :label="val.name" :value="val.id"></el-option>
								</el-select>
							</div>
							<!-- <el-checkbox-group v-else-if="column.isMulSelectBox" v-model="mulCheckBox.checkedItems">
								<el-checkbox v-for="item in getSelectOption(columnKey)" :label="item.name" :key="item.id">{{item.name}}</el-checkbox>
							</el-checkbox-group> -->
							<el-input v-else style="width:100%" v-model="configform[columnKey]"
								:clearable="true" :readonly="isShowUploadPic(columnKey)"></el-input>
						</el-col>
						<el-col :span="6" v-if="isShowUploadPic(columnKey)">
						    <m-upload-img :imgsAttrName="uploadDatas" :itemAttr="columnKey" :isMultImgs="false" 
						    	ref="uploadChild" @response-handler="afterUploadHandler">
						    </m-upload-img>
						</el-col>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="closeDialog">取 消</el-button>
					<el-button type="primary" @click="saveSubmit">确 定</el-button>
				</div>
			</el-dialog>
		<!--</el-col>-->
	</el-row>
</template>
<script>
	import {
		Message
	} from 'element-ui';
	import store from '../../store'
	export default {
		components:{},
		data() {
			return {
				tableDatalist:[],
				tableDataPage:[],
				goodsDatalist:[],
				specDatalist:[],
				goodsSpecDatalist:[],
				conditionForm: { //查询过滤的条件
					goodsName:''
				},
				tableColumn:[ 
					{
						columnName:'id', //主键字段，修改和删除的依赖列
						columnLabel:'ID',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:false, //是否在新增或修改对话框中显示该属性字段
					},
					{
						columnName:'goodsId',
						columnLabel:'产品名',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true, //是否在新增或修改对话框中显示该属性字段
						isInputSelectList:true,
						selectListData:[],
						dataQueryUrl:'goods/selectList'
					},
					{
						columnName:'goodsSpecificationIds',
						columnLabel:'产品特性',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
						isInputMutliAttr:true,
//						selectListData:[],
//						dataQueryUrl:'goodsSpecification/selectList'
					},
					{
						columnName:'goodsSn',
						columnLabel:'产品编号',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:false,
					},
					{
						columnName:'retailPrice',
						columnLabel:'零售价格',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'goodsNumber',
						columnLabel:'产品库存',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
					}
				],
				urlPaths:{
					queryList:'product/listAll',
					delByKey:'product/delete',
					insert:'product/add',
					updateByKey:'product/update',
					goodsQueryList:'goods/selectList',
					goodsSpecQueryList:'goodsSpecification/selectList',
					specQueryList:'specification/selectList',
				},
				configform: {},
				index: '',
				dialogVisible: false,
				dialogTitle:'新增',
				rules: {
				},
				currentRow: null,
				uploadImgs: {},
				uploadDatas:{
					clazz:'product',
					columnName:''
				},
				uploadFileList: [],
				mutliSelectOption:[],
			}
		}, 
		computed:{
			/**
			 * @author：01367604
			 * @function: 转换表中显示的属性值，将ID转换成名称
			 * @pramas: 
			 */
			tranColumnValue(columnName, columnValue){
				return function (columnName, columnValue){
//					console.log(columnName+ ': '+columnValue);
					var colElem;
					if (columnName === 'goodsId'){
						colElem = this.goodsDatalist.find((element) => (element.id == columnValue))
					} 
					if (colElem !=undefined && colElem.name !=undefined && colElem.name.length>0){
//						console.log(colElem);
						return colElem.name;
					} else {
						return columnValue;
					}
				}
			},
			/**
			 * @author：01367604
			 * @function: 转换新增和修改model框中显示的属性名称，将英文列名转换成中文描述
			 * @pramas: 
			 */
			transAttrName(value){
				return function (value){
//					#console.log(value);
					var resLabel;
					var colElem = this.tableColumn.find((element) => (element.columnName == value))
					if (colElem.columnLabel != undefined && colElem.columnLabel.length>0){
						resLabel= colElem.columnLabel;
					} else {
						resLabel= colElem.columnName;
					}
					return this.tranColumnValue(colElem.columnName, resLabel);
				}
			},
			/**
			 * @author：yc
			 * @function: 新增和修改model框是否显示（编辑）某属性
			 * @pramas: 
			 */
			isEditEnabled(value){
				return function (value){
					var colElem = this.tableColumn.find((element) => (element.columnName == value))
//					console.log(value + ": " + colElem.isModifyDialogEnabled);
					return colElem.isModifyDialogEnabled != undefined && colElem.isModifyDialogEnabled;
				}
			},
			/**
			 * @author：yc
			 * @function: 新增和修改model框中是否上传图片组件
			 * @pramas: 
			 */
			isShowUploadPic(value){
				return function (value){
					var colElem = this.tableColumn.find((element) => (element.columnName == value))
//					console.log(value + ": " + colElem.isPicColumn);
					return colElem.isPicColumn != undefined && colElem.isPicColumn;
				}
			},
			/**
			 * @author：01367604
			 * @function: 新增和修改model框中显示下拉框
			 * @pramas: 
			 */
			isShowSelectList(value){
				return function (value){
					var colElem = this.tableColumn.find((element) => (element.columnName == value))
					return colElem.isInputSelectList != undefined && colElem.isInputSelectList;
				}
			},
			/**
			 * @author：01367604
			 * @function: 新增和修改model框中一个表单项有多条属性信息
			 * @pramas: 
			 */
			isShowMutliElem(value){
				return function (value){
					var colElem = this.tableColumn.find((element) => (element.columnName == value))
					return colElem.isInputMutliAttr != undefined && colElem.isInputMutliAttr;
				}
			},
			/**
			 * @author：01367604
			 * @function: 新增和修改model框中下拉框数据获取
			 * @pramas: 
			 */
			getSelectOption(value){
				return function (value){
					var colElem = this.tableColumn.find((element) => (element.columnName == value))
					return colElem.selectListData;
				}
			},
		},
		beforeCreate(){
    	},
    	watch: {
////	      // 如果 `clientHeight` 发生改变，这个函数就会运行
//	      windowHeight: function () {
//	        console.log(this.windowHeight);
//      	this.$refs.leftMenu.style.height = (this.windowHeight- 80)+'px';
//	      }
	    },
    	mounted() {
    		this.initData();
		},
		methods: {
			initData(){
				this.querySpecificateData();
			},
			queryGoodsSpecData(goodId){
				/*查询接口*/
				this.$httpExt().get(this.urlPaths.goodsSpecQueryList, {
					goodId:goodId
				}).then((response) => {
					var rows= response.rows;
					console.log('Goods spec size:' + rows.length);
					for(let [index, item] of rows.entries()){
						item.index = index
					}
					this.goodsSpecDatalist = rows;
					console.log(this.goodsSpecDatalist);
					var goodSpecOption =[];
					for (var goodSpec of this.goodsSpecDatalist){
						var specElem = this.specDatalist.find((element) => (element.id === goodSpec.specificationId));
						var specOption = goodSpecOption.find((element) => (element.label === specElem.name));
						if (specOption==undefined || specOption==null){
							specOption = {'label':specElem.name, 'values':[], 'selectedValue':''};
							goodSpecOption.push(specOption);
						}
						var value = {'id':goodSpec.id, 'name': goodSpec.value};
						specOption.values.push(value);
					}
					this.mutliSelectOption = goodSpecOption;
					// console.log(this.mutliSelectOption);
				},(response) => {
					Message({
						message: '服务器请求失败，请重试！',
						type: 'warning'
					});
				});
			},
			querySpecificateData(){
				/*查询特性信息下拉列表数据接口*/
				this.$httpExt().get(this.urlPaths.specQueryList).then((response) => {
					var rows= response.rows;
					console.log('SpecificateData size:' + rows.length);
					this.specDatalist = rows;
				},(response) => {
					Message({
						message: '服务器请求失败，请重试！',
						type: 'warning'
					});
				});
			},
			queryTableData(){
				this.$refs.tableChild.initData();
			},
			/*选择一条数据*/
			handleCurrentChange(val) {
				if(!val) {
					return
				}
				this.currentRow = val;
				this.index = val.index+''
				console.log('this.currentRow ',this.currentRow);
				console.log('this.index ',this.index);
			},
			/*新增*/
			addFn(){
				this.dialogVisible = true;
				this.dialogTitle='新增';
				/*if(this.$refs['configform']!=undefined) {
					this.$refs['configform'].resetFields();
				}*/
				this.setFormData();
			},
			/*编辑*/
			editFn(){
				if(this.index) {
					this.dialogVisible = true;
					this.dialogTitle='编辑';
					this.setFormData();
				}else{
					Message({
						message: '请选择一条进行操作！',
						type: 'warning'
					});
				}
			},
			setFormData(){
				var form ={};
				for(let col of this.tableColumn){
					if (this.dialogTitle=='新增'){
						if (col.defaultValue != undefined && col.defaultValue!=''){
							form[col.columnName] = col.defaultValue;
						} else {
							form[col.columnName] = '';
						}
						this.mutliSelectOption=[];
					} else {
						form[col.columnName] = this.currentRow[col.columnName];
					}
				}
				this.configform = form;
			},
			/*删除*/
			deleteFn(){
				if(this.index) {
					this.$confirm('你确定要删除吗？', '删除提示', {
			          	confirmButtonText: '确定',
			          	cancelButtonText: '取消',
			          	type: 'warning'
			        }).then(() => {
			        	//调删除接口
			        	console.log(this.currentRow.id);
			        	this.$httpExt().get(this.urlPaths.delByKey, {
							id:this.currentRow.id
						}).then((response) => {
//							Message({
//								message: response.msg,
//								type: 'success'
//							});
							this.queryTableData();
						},(response) => {
							Message({
								message: '服务器请求失败，请重试！',
								type: 'warning'
							});
						});
			        });
				}else{
					Message({
						message: '请选择一条进行操作！',
						type: 'warning'
					});
				}
			},
			/*提交*/
			saveSubmit(){				
//				this.$refs.configform.validate((valid) => {
//					if(valid) {
//						
//						}
//					}
//				});
				var that = this;
				if(this.dialogTitle == '新增') {
					var url = this.urlPaths.insert;
				} else {
					var url = this.urlPaths.updateByKey;
				}
				var specIds =this.mutliSelectOption.map(op => op.selectedValue);
				that.configform['goodsSpecificationIds'] = specIds.join('_');
				console.log(that.configform);
				this.$httpExt().post(url,that.configform).then((response) => {
					if(response.succ == 'ok') {
						that.queryTableData();
						that.dialogVisible = false;
					}
				}, (data) => {
					Message({
						message: data.msg ? data.msg : '服务器请求失败，请重试！',
						type: 'warning'
					});
				});
			},
			closeDialog(){
				this.dialogVisible = false;
			},
			onSelectedDrug(columnName, item) {
				console.log('columnName:'+columnName+',item:'+item);
				if (columnName ==='goodsId'){
					var goodId = item;
					if (goodId != undefined && goodId!=''){
						this.queryGoodsSpecData(goodId);
					}
				}
	        },
			handleReset() {
				this.newlyFormVisible = false
			},
		    afterUploadHandler(data){
		    	this.configform[data.columnName] = data.res;
		    }
	    },
	}
</script>
<style>
.fl{
	float: left;
}
.product a{
	color: #20a0ff;
	text-decoration: none;
}

.customStyle{
    width:90%;
}

</style>